<template>
  <div>
    <div v-if="userrole == 2">
      <el-row :gutter="20">
        <el-col :span="1" :offset="3">
          <el-button type="primary" @click="back" icon="el-icon-arrow-left"
            >退出</el-button
          >
        </el-col>
        <el-col :span="16">
          <div v-show="editTopic == 1">
            <div class="center">
              <h3>发布心理评测</h3>
            </div>
            <el-form label-position="right" label-width="80px">
              <el-form-item label="测试名称">
                <el-input
                  v-model="title"
                  placeholder="请输入测试名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="测试类型">
                <el-select v-model="type" placeholder="请选择测试类型">
                  <el-option
                    v-for="type in types"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="上传封面">
                <el-upload
                  class="upload-demo"
                  action="/api/oss/uploadCover"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  list-type="picture"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="简介">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入测试简介"
                  v-model="brief"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="题目数量">
                <el-input
                  placeholder="题目数量,最大30"
                  v-model="topiccount"
                  clearable
                  style="width: 20%"
                  number
                >
                </el-input>
              </el-form-item>
              <el-form-item label="下一步">
                <el-button type="primary" @click="toEditTopic"
                  >编辑题目</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div v-show="editTopic == 2">
            <div class="center">
              <h3>题目 {{ currentTopic }} / {{ topiccount }}</h3>
            </div>
            <el-form label-position="right" label-width="80px">
              <el-form-item label="题目描述">
                <el-input
                  v-model="currentTopicInfo.questiontitle"
                  placeholder="请输入描述"
                ></el-input>
              </el-form-item>
              <el-form-item label="上传图片">
                <el-upload
                  class="upload-demo"
                  action="/api/oss/uploadCover"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-success="handleTopicSuccess"
                  :file-list="currentTopicInfo.fileList"
                  list-type="picture"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>

              <el-form-item label="选项数量">
                <el-select
                  v-model="currentTopicInfo.optionsCount"
                  placeholder="请选择"
                  @change="changeOptions()"
                >
                  <el-option
                    v-for="item in currentTopicInfo.countoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="操作">
                <el-button type="primary" @click="preQuestion"
                  >上一题</el-button
                >
                <el-button type="primary" @click="nextQuestion"
                  >下一题</el-button
                >
              </el-form-item>
              <el-form-item
                v-for="(option, index) in currentTopicInfo.options"
                :key="index"
                :label="`选项 ${index + 1}`"
              >
                <div>
                  <div>
                    选项：
                    <el-input
                      v-model="option.value"
                      :readonly="true"
                    ></el-input>
                  </div>
                  <div>
                    描述：
                    <el-input
                      v-model="option.title"
                      placeholder="请输入选项描述"
                    ></el-input>
                  </div>
                  <div>
                    分值：
                    <el-input
                      v-model.number="option.score"
                      placeholder="请输入分值"
                      type="number"
                    ></el-input>
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="下一步" v-if="isLastTopic">
                <el-button type="primary" @click="editTopic = 3"
                  >编辑结果</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div v-show="editTopic == 3">
            <div class="center">
              <h3>编辑结果</h3>
            </div>
            <el-form label-position="right" label-width="80px">
              <el-form-item label="结果数量">
                <el-select
                  v-model="resCount"
                  placeholder="请选择"
                  @change="changeResults()"
                >
                  <el-option
                    v-for="item in countresults"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                v-for="(res, index) in resultList"
                :key="res.id"
                :label="`结果 ${index + 1}`"
              >
                <div>
                  达到分值：
                  <el-input v-model="res.score" placeholder="分值"></el-input>
                </div>
                <div>
                  结果描述：
                  <el-input v-model="res.res" placeholder="结果描述"></el-input>
                </div>
              </el-form-item>
              <el-form-item label="提交">
                <el-button type="primary" @click="submit">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <div v-else class="center">
      <div>请先登录咨询师账号~</div>
    </div>
  </div>
</template>

<script>
export default {
  created() {
    this.generateTopicOptions();

    let countresults = [];
    // 初始化 countoptions 数组
    for (let j = 0; j < 5; j++) {
      // 初始化10个选项
      countresults.push({ id: j, value: j + 1, label: j + 1 + "个" });
    }
    this.countresults = countresults;
    this.resultList.push(this.result);
  },
  computed: {
    //当前角色
    userrole() {
      return localStorage.getItem("userrole");
    },
    // 获取当前题目的选项信息数组长度
    currentTopicOptionsLength() {
      return this.topicOptions[this.currentTopic - 1].countoptions.length;
    },
    // 获取当前题目的信息
    currentTopicInfo() {
      return this.topicOptions[this.currentTopic - 1];
    },
    // 当前题目是否为最后一题
    isLastTopic() {
      return this.currentTopic == this.topiccount;
    },
  },
  data() {
    return {
      title: "", //测试名
      type: 2, //类型
      brief: "", //简介
      cover: "", //封面
      topiccount: "3", //题目数量

      fileList: [],
      editTopic: 1, //1.测试基本信息填写 2.题目信息填写 3.答案信息填写
      types: [
        {
          value: 1,
          label: "情感",
        },
        {
          value: 2,
          label: "性格",
        },
        {
          value: 3,
          label: "健康",
        },
        {
          value: 4,
          label: "职场",
        },
        {
          value: 5,
          label: "人际",
        },
        {
          value: 6,
          label: "能力",
        },
      ],
      currentTopic: 1, //当前题目

      //选项信息
      option: { optionid: "", value: "", title: "", score: 0 },
      //题目信息
      topicOption: {
        questiontitle: "", //题目描述
        fileList: [], //图片存放
        questionImage: "", //题目图片
        optionsCount: 1, //选项数量
        countoptions: [], //用于存放select绑定的选项数量对应的选择
        options: [], //选项信息，用于存放选项信息
      },
      topicOptions: [], //题目数组,用来存放题目的信息

      countresults: [], //选择列表
      resCount: 1, //结果条数
      result: { id: 0, score: 0, res: "" }, //达到分数的结果
      resultList: [], //结果列表
    };
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一张封面图片，请先删除已添加的封面图片`);
    },
    //图片上传成功回调
    handleSuccess(response, file, fileList) {
      let pre = this.$store.getters.getCoverPre;
      let cover = pre + response.fileName;
      console.log(cover);
      this.cover = cover;
      this.fileList = fileList.slice(-1); // 只保留最新上传的图片
      this.$message.success("上传成功");
    },
    handleTopicSuccess(response, file, fileList) {
      let pre = this.$store.getters.getCoverPre;
      let cover = pre + response.fileName;
      console.log(cover);
      this.currentTopicInfo.questionImage = cover;
      this.currentTopicInfo.fileList = fileList.slice(-1); // 只保留最新上传的图片
      this.$message.success("上传成功");
    },
    //返回
    back() {
      this.$router.back();
    },
    // 在 methods 部分添加以下方法
    generateTopicOptions() {
      this.topicOptions = []; // 清空之前的题目数据
      const topicCountInt = parseInt(this.topiccount);

      let countoptions = [];
      // 初始化 countoptions 数组
      for (let j = 0; j < 10; j++) {
        // 初始化10个选项
        countoptions.push({ value: j + 1, label: j + 1 + "个" });
      }

      for (let i = 0; i < topicCountInt; i++) {
        const topicOption = {
          questiontitle: "", // 题目描述
          questionImage: "", // 题目图片
          optionsCount: 1, // 选项数量，默认为1
          countoptions: countoptions, //
          options: [{ optionid: 1, value: "A", title: "", score: 0 }], // 选项信息，初始为空
        };
        this.topicOptions.push(topicOption);
      }
    },

    // 前往编辑题目，在 toEditTopic 方法中调用生成题目数据的方法
    toEditTopic() {
      if (this.checkFormNotEmpty()) {
        this.editTopic = 2;
        this.generateTopicOptions(); // 生成题目数据
      }
    },

    //检查form数据
    checkFormNotEmpty() {
      if (!this.title) {
        this.$message.error("评测标题不能为空");
        return false;
      }
      if (!this.cover) {
        this.$message.error("请上传封面");
        return false;
      }
      if (!this.brief) {
        this.$message.error("评测简介不能为空");
        return false;
      }
      if (!this.topiccount) {
        this.$message.error("题目数量不能为空");
        return false;
      }

      const topicCountInt = parseInt(this.topiccount);
      if (
        isNaN(topicCountInt) ||
        topicCountInt < 1 ||
        topicCountInt > 30 ||
        this.topiccount !== topicCountInt.toString()
      ) {
        this.$message.error("题目数量必须是1到30之间的整数");
        return false;
      }
      return true;
    },

    changeOptions() {
      // 当选项数量改变时重新生成选项
      const currentTopicOptions = this.topicOptions[this.currentTopic - 1];
      const newOptionsCount = parseInt(currentTopicOptions.optionsCount);
      const currentOptionsCount = currentTopicOptions.options.length;

      if (newOptionsCount > currentOptionsCount) {
        // 如果新的选项数量大于当前选项数量，则添加新选项
        const startId =
          currentOptionsCount > 0
            ? currentTopicOptions.options[
                currentOptionsCount - 1
              ].value.charCodeAt(0) + 1
            : 65; // Start from 'A' if no options yet
        for (let i = 0; i < newOptionsCount - currentOptionsCount; i++) {
          // 递推大写字母作为 value
          const value = String.fromCharCode(startId + i);
          currentTopicOptions.options.push({
            optionid: currentOptionsCount + 1 + i,
            value: value,
            title: "",
            score: 0,
          });
        }
      } else if (newOptionsCount < currentOptionsCount) {
        // 如果新的选项数量小于当前选项数量，则删除多余选项
        currentTopicOptions.options.splice(newOptionsCount);
      }
    },

    //上一题
    preQuestion() {
      if (this.currentTopic > 1) {
        this.currentTopic--; // Move to the previous question
      }
    },
    //下一题
    nextQuestion() {
      if (this.currentTopic < this.topiccount) {
        this.currentTopic++; // Move to the next question
      }
    },
    changeResults() {
      this.resultList = []; // 清空之前的结果数据

      for (let i = 0; i < this.resCount; i++) {
        const resultItem = {
          id: i, //id
          score: 0, // 分数
          res: "", // 结果描述
        };
        this.resultList.push(resultItem);
      }
    },
    //获取提交值RichEvation
    getRichEvation() {
      //问题列表
      let richEvaluationQuestionDtoList = [];
      //遍历问题
      for (let topic of this.topicOptions) {
        //处理options
        let options = topic.options.map((option) => {
          return {
            optionid: null,
            questionid: null,
            value: option.value,
            title: option.title,
            score: option.score,
            sort: null,
          };
        });

        richEvaluationQuestionDtoList.push({
          evaluateQuestion: {
            questionid: null,
            evaluateid: null,
            title: topic.questiontitle,
            sort: null,
            image: topic.questionImage,
          },
          questionOptionList: options,
        });
      }

      //final
      let richEvaluationDto = {
        evaluate: {
          evaluateid: null,
          type: this.type,
          title: this.title,
          brief: this.brief,
          evacount: 0,
          evareplycount: 0,
          createdate: null,
          cover: this.cover,
          topiccount: this.topiccount,
          evaresult: this.getRes(),
        },
        richEvaluationQuestionDtoList: richEvaluationQuestionDtoList,
      };

      return richEvaluationDto;
    },
    //获取结果值
    getRes() {
      let res = "";
      for (let result of this.resultList) {
        res = res + result.score + "-" + result.res + ";";
      }
      return res;
    },
    //提交
    submit() {
      this.$request.postHttp({
        url: "/evaluate/insertRichEvaluate",
        data: this.getRichEvation(),
        success: (data) => {
          console.log(data);
          if (data.code == 200) {
            this.$message({
              message: "提交成功！",
              type: "success",
            });
            this.$router.back();
          }
        },
        error: (error) => {},
      });
    },
  },
};
</script>

<style scoped>
.center {
  display: flex;
  justify-content: center;
}
</style>